#!/usr/bin/env bash


help(){
    cat<<__EOF__
Usage: m screensaver [OPTIONS]

Description: Launch the screensaver, check its status, or set password requirement to unlock.

Options:
  --help                             Show this help message
  --askforpassword <enable|disable>  Get or set password requirement to unlock the screensaver.
                                     If no argument is provided, it will display the current setting.

Examples:
  m screensaver                            # launch screensaver
  m screensaver --askforpassword           # display current askforpassword setting
  m screensaver --askforpassword disable   # disable password requirement to unlock
__EOF__
}

askforpassword(){
    case $1 in
        enable)
            defaults write com.apple.screensaver askForPassword -int 1
            echo "Screensaver askforpassword: enabled"
            ;;
        disable)
            defaults write com.apple.screensaver askForPassword -int 0
            echo "Screensaver askforpassword: disabled"
            ;;
        *)
            local value="$(defaults read com.apple.screensaver askForPassword 2>/dev/null)"
            if [ -z "${value}" ] || [ "${value}" -eq 0  ]; then
                echo "Screensaver askforpassword: disabled"
            else
                echo "Screensaver askforpassword: enabled"
            fi
            ;;
    esac
}

screensaver(){
    # ScreenSaverEngine.app was moved in 10.13 (High Sierra).
    LOCATION_OLD='/System/Library/Frameworks/ScreenSaver.framework/Resources/ScreenSaverEngine.app'
    LOCATION='/System/Library/CoreServices/ScreenSaverEngine.app'
    if [ -e ${LOCATION} ]; then
        open ${LOCATION}
    elif [ -e ${LOCATION_OLD} ]; then
        open ${LOCATION_OLD}
    else
        echo 'Could not find ScreenSaverEngine.app'
    fi
}


case $1 in
    --help)
        help
        ;;
    --askforpassword)
        shift
        askforpassword $@
        ;;
    *)
        screensaver
        ;;
esac
